package cn.itcast.star.graph.core.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.itcast.star.graph.core.dto.common.Result;
import cn.itcast.star.graph.core.dto.common.ResultCode;
import cn.itcast.star.graph.core.pojo.User;
import cn.itcast.star.graph.core.utils.JwtUtil;
import cn.itcast.star.graph.core.utils.UserUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 用户请求拦截器
 */
public class UserInterceptor implements HandlerInterceptor {

    /**
     * 处理controller之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验是否为登录请求
        String uri = request.getRequestURI();
        if (uri.contains("/api/1.0/user/login") || uri.contains("/error")) {
            return true;
        }

        //验证token是否为空
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
//        if (StrUtil.isEmpty(token) || JwtUtil.verify(token)) {    //token非空校验&jwt解码校验
        if (StrUtil.isEmpty(token)) {    //token非空校验&jwt解码校验
            writeAuthorizationFiled(response);
            return false;
        }
        //解析token
        //获取用户信息并存入线程池变量
        User user = JwtUtil.getUser(token);
        if (user == null) {
            writeAuthorizationFiled(response);
            return false;
        }
        UserUtil.save(user);
        return true;
    }

    /**
     * 封装响应未授权的返回结果
     * @param response
     */
    public static void writeAuthorizationFiled(HttpServletResponse response) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        Result<Object> failed = Result.failed(ResultCode.ACCESS_UNAUTHORIZED);
        String jsonStr = JSONUtil.toJsonStr(failed);
        try {
            PrintWriter writer = response.getWriter();
            writer.write(jsonStr);
            writer.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理controller之后
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 做完mvc处理之后,返回结果之前
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtil.remove();
    }
}
